package com.vnp.vchat.httpclient;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import android.content.Context;
import android.util.Base64;
import android.util.Log;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.vnp.vchat.util.PreferenceHelper;

public class HttpClientHelper {
	// khai bao duong dan api chung
	private static final String BASE_URL = "http://vchat.vn";
	
	//update device id
	private static final String UPDATE_DEVICEID = "/service/adevice.php";
	
	
	// cai dat
	private static final String SETTINGS = "/service/usetting.php";
	
	// lay danh sach nguoi da chat
	private static final String GET_DS_CHAT = "/service/hischat.php";
	
	// lay history chat
	private static final String GET_HASH_CHAT = "/service/gsct.php";
	private static final String GET_HIS_CHAT = "/service/chistory.php";
	
	// http chat
	private static final String ACTION_CHAT = "/service/send.php";
	
	
	
	
	//--------------------------vChat v 2.0 ----------------------------//
	// getAccount by phone
	private static final String BASE_URL_VATGIA = "https://id.vatgia.com";
	private static final String GET_ACCOUNT_BY_PHONE = "/api/v1/account/getAccountByPhone";
	
	private static final String LOGIN_BY_PHONE_OR_EMAIL = "/service/login_api_app.php";
	
	private static final String SEND_PHONE = "/api/v1/account";
	private static final String SEND_CODE = "/api/v1/account/verifyPhone";
	private static final String UPDATE_INFO = "/api/v1/account/updateInfo";
	
	private static final String SEARCH_USER = "/service/app_search_user.php";
	
	private static final String GET_CONTACT = "/service/app_api_get_contact.php";
	private static final String SEND_CONTACT = "/service/app_api_add_contact.php";
		
	
	
	// dang nhap qua mail hoac so dt
	
	// khai bao context
	private Context context;
	
	// khai bao cac thanh phan thao tac client va server
	private static AsyncHttpClient client = new AsyncHttpClient();
	private AsyncHttpResponseHandler  asyncHttpResponseHandler;
	
	
	
	
	
	// khai bao file luu tam
	private PreferenceHelper preferenceHelper;
	
	// contructor
	public HttpClientHelper(AsyncHttpResponseHandler asyncHttpResponseHandler, Context context) {
		this.asyncHttpResponseHandler = asyncHttpResponseHandler;
		this.context = context;
		preferenceHelper = new PreferenceHelper(context);
	}
	
	public HttpClientHelper(AsyncHttpResponseHandler asyncHttpResponseHandler) {
		this.asyncHttpResponseHandler = asyncHttpResponseHandler;
	}
	
	public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
		try {
			client.get(getAbsoluteUrl(BASE_URL, url), params, responseHandler);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// phan rieng
	public static void get(String url, AsyncHttpResponseHandler responseHandler) {
		try {
			client.get(url, null, responseHandler);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
		try {
			client.post(getAbsoluteUrl(BASE_URL,url), params, responseHandler);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void postWithHeader(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
		String a="mobile-android-que/wXrb3AKSFfjQhLUkT5RoXxQ35CyEVuj28z4";
		try {
			String credentials = "mobile-android-que" + ":" + "wXrb3AKSFfjQhLUkT5RoXxQ35CyEVuj28z4";  
			String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); 
			client.addHeader("Authorization", "Basic " + base64EncodedCredentials);
			
			client.post(getAbsoluteUrl(BASE_URL_VATGIA,url), params, responseHandler);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
//		MessageDigest md5 = null;
//	    try {
//	      md5 = MessageDigest.getInstance("MD5");
//	    } catch(NoSuchAlgorithmException e) {
//	      e.printStackTrace();
//	    }
//	    md5.update("wXrb3AKSFfjQhLUkT5RoXxQ35CyEVuj28z4".getBytes());
//	    String digestedPass = digest2HexString(md5.digest());
//	    
//		try {
//			String credentials = "mobile-android-que" + ":" + digestedPass;  
//			//String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); 
//			client.addHeader("Authorization", "Digest " + credentials);
//			
//			client.post(getAbsoluteUrl(BASE_URL_VATGIA,url), params, responseHandler);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		
//		
	}
	

	private static String digest2HexString(byte[] digest)
	{
	   String digestString="";
	   int low, hi ;

	   for(int i=0; i < digest.length; i++)
	   {
	      low =  ( digest[i] & 0x0f ) ;
	      hi  =  ( (digest[i] & 0xf0)>>4 ) ;
	      digestString += Integer.toHexString(hi);
	      digestString += Integer.toHexString(low);
	   }
	   return digestString ;
	}
	
	// get url voi tham so truyen len
	private static String getUrlWithParams(String base, String relativeUrl, List<BasicNameValuePair> params) {
		String url = getAbsoluteUrl(base, relativeUrl);
		for (int i = 0; i < params.size(); i++) {
			BasicNameValuePair b = params.get(i);
			url+="&"+b.getName()+"="+b.getValue();
		}
		url = url.replace(" ", "%20");
		return url;
	}
	
	// get url post
	private static String getUrlPostWithParams(String base, String relativeUrl, RequestParams params) {
		String url = getAbsoluteUrl(base, relativeUrl);
		RequestParams r = params;
		url+="?"+r;
		url = url.replace(" ", "%20");
				
		return url;
	}
	
	
	// tao duong dan api 
	private static String getAbsoluteUrl(String base, String relativeUrl) {
		return base + relativeUrl + "/";
	}
	
	// trang cai dat
	public void postSettings(String sso_id, String hash, int st_notifi,int st_feed, int st_showmsg) {
		RequestParams params = new RequestParams();
		params.add("sso_id", sso_id);
		params.add("hash", hash);
		params.add("st_notifi", String.valueOf(st_notifi));
		params.add("st_feed", String.valueOf(st_feed));
		params.add("st_showmsg", String.valueOf(st_showmsg));
		post(SETTINGS, params, asyncHttpResponseHandler);
		Log.i("URL", "URL: "+getUrlPostWithParams(BASE_URL, SETTINGS, params));
	}
	
	// get danh sach nguoi da chat
	public void getDanhsachChat(String sso_id, String hash, int page, int groupmsg){
		RequestParams params = new RequestParams();
		params.add("sso_id", sso_id);
		params.add("hash", hash);
		params.add("page", String.valueOf(page));
		params.add("groupmsg", String.valueOf(groupmsg));
		post(GET_DS_CHAT, params, asyncHttpResponseHandler);
		Log.i("URL", "URL: "+getUrlPostWithParams(BASE_URL, GET_DS_CHAT, params));
	}
	
	// lay lich su tro chuyen
	
	public void getHash(int to_id, int send_id, String token, int groupmsg){
		
		RequestParams params = new RequestParams();
		params.add("to_id", String.valueOf(to_id));
		params.add("send_id", String.valueOf(send_id));
		params.add("token", token);
		params.add("groupmsg", String.valueOf(groupmsg));
		post(GET_HASH_CHAT, params, asyncHttpResponseHandler);
		Log.i("URL", "URL: "+getUrlPostWithParams(BASE_URL, GET_HASH_CHAT, params));
	}
	
	
	public void getHistoryChat(int send_id, int to_id, String hash, int page, int groupmsg){
		RequestParams params = new RequestParams();
		params.add("send_id", String.valueOf(send_id));
		params.add("to_id", String.valueOf(to_id));
		params.add("hash", hash);
		params.add("page", String.valueOf(page));
		params.add("groupmsg", String.valueOf(groupmsg));
		post(GET_HIS_CHAT, params, asyncHttpResponseHandler);
		Log.i("URL", "URL: "+getUrlPostWithParams(BASE_URL, GET_HIS_CHAT, params));
	}
	
	
	// action chat
	public void sendChatMsg(int send_id, int to_id, String hash, String type, int groupmsg, String msg, String name, long vgc, long vgc_key){
		RequestParams params = new RequestParams();
		params.add("send_id", String.valueOf(send_id));
		params.add("to_id", String.valueOf(to_id));
		params.add("hash", hash);
		params.add("type", type);
		params.add("groupmsg", String.valueOf(groupmsg));
		params.add("message", msg);
		params.add("name", name);
		params.add("vgc_rand", String.valueOf(vgc));
		params.add("support_id", String.valueOf(send_id));
		params.add("vgc_key", String.valueOf(vgc_key));
		post(ACTION_CHAT, params, asyncHttpResponseHandler);
		Log.i("URL", "URL: "+getUrlPostWithParams(BASE_URL, ACTION_CHAT, params));
	}
	
	// update deviceid
	public void updateDeviceID(int sso_id, String hash, String device_type, String device_id, String imei){
		RequestParams params = new RequestParams();
		params.add("sso_id", String.valueOf(sso_id));
		params.add("hash", hash);
		params.add("device_type", device_type);
		params.add("device_id", device_id);
		params.add("emei", imei);
		post(UPDATE_DEVICEID, params, asyncHttpResponseHandler);
		Log.i("URL", "URL: "+getUrlPostWithParams(BASE_URL, UPDATE_DEVICEID, params));
	}
	
	/** -----------------------vChat 2.0 httpclient-------------------------------*/
	
	
	public void getAccountByPhone(String phone){
		RequestParams params = new RequestParams();
		params.add("phone", phone);
		
		postWithHeader(GET_ACCOUNT_BY_PHONE, params, asyncHttpResponseHandler);
	}
	
	
	//--- login by phone or email
	public void loginByPhoneOrEmail(String userName, String pass, String hash, String key){
		RequestParams params = new RequestParams();
		params.add("username", userName);
		params.add("password", pass);
		params.add("hash", hash);
//		params.add("key", key);
		
		post(LOGIN_BY_PHONE_OR_EMAIL, params, asyncHttpResponseHandler);
		Log.i("URL", "URL: "+getUrlPostWithParams(BASE_URL, LOGIN_BY_PHONE_OR_EMAIL, params));
	}
	
	// ---- send phone get verifiy code --- //
	public void sendPhone(String phone){
		RequestParams params = new RequestParams();
		params.add("phone", phone);
		
		postWithHeader(SEND_PHONE, params, asyncHttpResponseHandler);
		Log.i("URL", "URL: "+getUrlPostWithParams(BASE_URL_VATGIA, SEND_PHONE, params));
	}
	
	// ---- send code  --- //
	public void sendCode(String acc_id, String code){
		RequestParams params = new RequestParams();
		params.add("acc_id", acc_id);
		params.add("code", code);
		
		postWithHeader(SEND_CODE, params, asyncHttpResponseHandler);
		Log.i("URL", "URL: "+getUrlPostWithParams(BASE_URL_VATGIA, SEND_CODE, params));
	}
	
	//------------update info----------//
	public void updateInfo(String acc_id, String fullName, String email, String pass, byte[] b){
		RequestParams params = new RequestParams();
		params.put("acc_id", acc_id);
		params.put("full_name", fullName);
		params.put("email", email);
		params.put("password", pass);
		
		params.put("avatar", b);
		
		postWithHeader(UPDATE_INFO, params, asyncHttpResponseHandler);
		Log.i("URL", "URL: "+getUrlPostWithParams(BASE_URL_VATGIA, UPDATE_INFO, params));
	}
	
	
	//------------search user----------//
	public void searchUser(int user_id, String hash, String keyword){
		RequestParams params = new RequestParams();
		params.put("user_id", String.valueOf(user_id));
		params.put("hash", hash);
		params.put("keyword", keyword);
		
		post(SEARCH_USER, params, asyncHttpResponseHandler);
		Log.i("URL", "URL: "+getUrlPostWithParams(BASE_URL, SEARCH_USER, params));
	}
	
	
	//------------get Contact----------//
	public void getContact(String user_id, String hash, int page){
		RequestParams params = new RequestParams();
		params.put("user_id", user_id);
		params.put("hash", hash);
		params.put("page", String.valueOf(page));
		
		
		post(GET_CONTACT, params, asyncHttpResponseHandler);
		Log.i("URL", "URL: "+getUrlPostWithParams(BASE_URL, GET_CONTACT, params));
	}
	
	
	//------------send Contact----------//
	public void sendContact(String userId, JSONArray listContact, String hash){
		RequestParams params = new RequestParams();
		params.put("user_id", userId);
		params.put("list", listContact.toString());
		params.put("hash", hash);
		post(SEND_CONTACT, params, asyncHttpResponseHandler);
//		client.post("http://aotasoft.com/extra/contact.php", params, asyncHttpResponseHandler);
		Log.i("URL", "URL: "+getUrlPostWithParams(BASE_URL, SEND_CONTACT, params));
	}
	
}

